# -*- coding: utf-8 -*-

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core import serializers

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User, Group

from django import forms
from captcha.fields import ReCaptchaField

from accounts.models import UserProfile, Messages
from achievements.views import ReCaptchaForm

from achievements.models import Achievement, SubAchievement, Fulfilment, Category, Evidence

from achievements.forms import *
import types, json

SELECT_ALLUSERS_QUERY = 'SELECT * FROM accounts_userprofile'
SELECT_ACHIEV_LIST_QUERY = 'SELECT * FROM achievements_fulfilment WHERE user.username = %s'


class NLUserCreationForm(UserCreationForm):
    captcha = ReCaptchaField(attrs={'theme' : 'blackglass'}, error_messages=dict(required='Táto položka je povinná.'))
    username = forms.RegexField(regex=r'^[a-z\d]+$', max_length=30, min_length=6,
                                error_messages={'invalid':'Meno obsahuje neplatné znaky.',
                                                'max_length':'Meno presahuje povolenú dĺžku znakov.',
                                                'min_length':'Meno nedosahuje požadovanú dĺžku znakov.'})
    
    password1 = forms.CharField(widget=forms.PasswordInput, error_messages={'required':'Táto položka je povinná.', 'invalid':'Nesprávny formát.'})
    password2 = forms.CharField(widget=forms.PasswordInput, error_messages={'required':'Táto položka je povinná.', 'invalid':'Nesprávny formát.'})


def register(request):

    if request.method == 'POST':        
        form = NLUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            
            login(request, user)
            
            return render_to_response('accounts/register.html', 
                { 'success' : True }, context_instance=RequestContext(request))
        else:
            return render_to_response('accounts/register.html', 
                {'error_message': "Registration error.", 'form': form, 'success' : False }, context_instance=RequestContext(request))
    else:
        form = NLUserCreationForm()
        
    return render_to_response('accounts/register.html', {'form': form, 'success' : False }, context_instance=RequestContext(request))


def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')
    
    
def show_current_user(request):
    
    if not request.user.is_authenticated:
        return
        
    return show_user(request, request.user.username)
        

def user_json(request, user_id):
    user_profile_list = UserProfile.objects.filter(user__username = user_id)
    
    data = None
    
    if len(list(user_profile_list)) > 0:
        data = serializers.serialize("json", user_profile_list)
        
        data = json.loads(data)

        for d in data:
            del d['model']

        data = json.dumps(data)
        
    return render_to_response('api.html', {'data': data }, context_instance=RequestContext(request))

    
# Vyparsuj a zobraz uzivatelsku stranku
def show_user(request, user_id, extras=None):
    
    user_profile = None
    
    achiev_list = None
    fulf_done_list = []
    fulf_inprogress_list = []
    evidences = None
    
    user_profile_list = UserProfile.objects.filter(user__username = user_id)
    
    if len(list(user_profile_list)) > 0:
        user_profile = user_profile_list[0]
        
        tmp_fulfs = Fulfilment.objects.filter(user = user_profile.user)
        achiev_list = Achievement.objects.filter(author = user_profile.user)
                
        if len(list(tmp_fulfs)) > 0:

            for fulf in tmp_fulfs:
                if fulf.progress == fulf.achievement.progressMax and fulf.awarded:
                    fulf_done_list.append(fulf)
                else:
                    fulf_inprogress_list.append(fulf)
                    
        if achiev_list is not None:
	  if isinstance(achiev_list, types.ListType):
	    achiev_list = [achiev_list]
	  if len(list(achiev_list)) == 0:
	    achiev_list = None 

    if len(fulf_done_list) == 0:
        fulf_done_list = None
        
    if len(fulf_inprogress_list) == 0:
        fulf_inprogress_list = None
    
    messages = None
    
    if request.user.is_authenticated() and user_profile:
        if request.user == user_profile.user:
            sent_messages = Messages.objects.filter(recipient = user_profile.user, hidden = False)
            if len(list(sent_messages)) > 0:
                messages = list(sent_messages)
            
            if request.method == 'POST':
                if 'avatar_image' in request.FILES:
                    request.user.userprofile.image = request.FILES['avatar_image']
                    request.user.userprofile.save()        
    

    return render_to_response('accounts/user.html',
        { 'user_profile':user_profile, 'data':extras, 'achiev_list':achiev_list, 'fulf_inprogress_list':fulf_inprogress_list, 'fulf_done_list':fulf_done_list, 'messages':messages, 'evidences':evidences },
        context_instance=RequestContext(request))
        
        
def add_friend(request, user_id):
    
    # 0 - add friend
    # 1 - remove friends
    # 2 - message friend
    
    operation = 0
    
    # 0 - show message textarea
    # 1 - request already sent
    # 2 - request successfully sent
    # 3 - sending to self
    # 4 - already friends
    
    state = 0
    
    user_id_list = User.objects.filter(username = user_id)
    user = None
    if len(list(user_id_list)) > 0:
        user = user_id_list[0]
        
    if request.user.is_authenticated() and user:
        if request.user == user:
            state = 3
        else:
            friends_already = UserProfile.objects.filter(user = user, friends__id = request.user.id)
            if len(list(friends_already)) > 0:
                state = 4
            else:
                sent_messages = Messages.objects.filter(author = request.user, recipient = user, message_type = 'FR', hidden = False)
                if len(list(sent_messages)) > 0:
                    state = 1
                elif request.method == 'POST':
                    state = 2
                    
                    message = Messages()
                    message.text = request.POST['message'] if len(request.POST['message']) > 0 else 'Bez správy.'
                    message.author = request.user
                    message.recipient = user
                    message.header = 'Máte novú žiadosť o priateľstvo'
                    message.message_type = 'FR'
                    
                    message.save()
        
    
    return render_to_response('accounts/friend.html',
        {'state':state, 'friend':user, 'operation':operation},
        context_instance=RequestContext(request))


def remove_friend(request, user_id):
    
    operation = 1 # Remove friend
    
    state = 0
    
    user_id_list = User.objects.filter(username = user_id)
    user = None
    if len(list(user_id_list)) > 0:
        user = user_id_list[0]
        
    if request.user.is_authenticated() and user:
        if request.user == user:
            state = 1 # Removing self
        elif request.method == 'POST':
            friends_already = UserProfile.objects.filter(user = user, friends__id = request.user.id)
            if len(list(friends_already)) == 0:
                state = 2 # Not friends
            else:
                state = 3 # Removing successfull
                friends_already[0].friends.remove(request.user)
        
    return render_to_response('accounts/friend.html',
        {'state':state, 'friend':user, 'operation':operation},
        context_instance=RequestContext(request))

def message_friend(request, user_id):
    operation = 2 # Message friend
    state = 0
    
    user_id_list = User.objects.filter(username = user_id)
    
    user = None
    captcha = None
    
    message = None
    header = None
    
    errors = {}
    
    if len(list(user_id_list)) > 0:
        user = user_id_list[0]
        
    if request.user.is_authenticated() and user:
        friends_already = UserProfile.objects.filter(user = user, friends__id = request.user.id)
        if len(list(friends_already)) == 0:
            captcha = ReCaptchaForm()
        
        if request.user == user:
            state = 1 # Messaging self
        elif request.method == 'POST':
            
            message = request.POST['message']
            header = request.POST['header']
            
            if len(message) == 0:
                errors['message'] = 'Správa nesmie byť prázdna.'
            
            if captcha:
                captcha = ReCaptchaForm(request.POST)
                if captcha.is_valid():
                    captcha = None
                else:
                    return render_to_response('accounts/friend.html',
                        { 'state':state, 'friend':user, 'operation':operation, 'captcha':captcha, 'message':message, 'header':header, 'errors':errors},
                        context_instance=RequestContext(request))
            
            if len(errors) == 0:
                state = 2
                
                user_message = Messages()
                user_message.text = message
                user_message.author = request.user
                user_message.recipient = user
                user_message.header = (u'Správa od ' + user.username) if len(header) == 0 else header
                user_message.message_type = 'UM'
                
                user_message.save()
    
    return render_to_response('accounts/friend.html',
        { 'state':state, 'friend':user, 'operation':operation, 'captcha':captcha, 'errors':errors },
        context_instance=RequestContext(request))


def show_users_page(request):
    
    result_list = None
    
    user_list = dict.fromkeys(UserProfile.objects.all())
    if len(user_list) == 0:
        user_list = None
        
    for u in user_list.keys():
        user_list[u] = {}
        user_list[u]['countdone'] = Fulfilment.objects.filter(user = u.user).count()
        user_list[u]['countmade'] = Achievement.objects.filter(author = u.user).count()
    
    if request.user.is_authenticated() and user_list:
        for u, d in user_list.iteritems():
            if UserProfile.objects.filter(user = u.user, friends__id = request.user.id).count() > 0:
                d['friends'] = True
            else:
                d['friends'] = False
                
    category_list = dict.fromkeys(Category.objects.all())
    if len(category_list) == 0:
        category_list = None
    
            
    return render_to_response('accounts/users.html',
	    {'user_list': user_list, 'result_list':result_list, 'category_list':category_list},
	    context_instance=RequestContext(request))